// HTTP 模块统一导出
// @/utils/http/index.ts

import { HttpClient } from './HttpClient'
import { HttpError, ErrorType } from './HttpError'
import { useAuthStore } from '../../stores/modules/auth'
import type { 
  RequestConfig, 
  BaseResponse, 
  PageResponse,
  CancelToken,
  UploadConfig,
  DownloadConfig
} from '@/types/http'

// 创建默认实例
const httpClient = new HttpClient({
  baseURL: import.meta.env.VITE_API_URL || 'https://api.volcore.xyz',
  timeout: 30000,
  enableCache: true,
  maxConcurrent: 6,
  retryConfig: {
    count: 3,
    delay: 1000,
    enableExponentialBackoff: true
  }
})

// 设置默认请求拦截器
httpClient.interceptors.request.use(
  (config) => {
    // 可以在这里添加全局的请求处理
    return config
  },
  (error) => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 设置默认响应拦截器
httpClient.interceptors.response.use(
  (response) => {
    // 可以在这里添加全局的响应处理
    return response
  },
  (error) => {
    console.error('响应拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 导出实例方法
export const http = {
  get: httpClient.get.bind(httpClient),
  post: httpClient.post.bind(httpClient),
  put: httpClient.put.bind(httpClient),
  delete: httpClient.delete.bind(httpClient),
  request: httpClient.request.bind(httpClient)
}

// 文件上传
export async function uploadFile(config: UploadConfig): Promise<any> {
  return new Promise((resolve, reject) => {
    const authStore = useAuthStore()
    const uploadTask = uni.uploadFile({
      url: httpClient['baseURL'] + config.url,
      filePath: config.filePath,
      name: config.name || 'file',
      header: {
        'Authorization': `Bearer ${authStore.token}`,
        ...config.header
      },
      formData: config.formData,
      success: (res) => {
        if (res.statusCode === 200) {
          try {
            const data = JSON.parse(res.data)
            resolve(data)
          } catch (e) {
            resolve(res.data)
          }
        } else {
          reject(new HttpError(
            '文件上传失败',
            ErrorType.SERVER,
            undefined,
            res.statusCode
          ))
        }
      },
      fail: (err) => {
        reject(new HttpError(
          err.errMsg || '文件上传失败',
          ErrorType.NETWORK
        ))
      }
    })

    // 处理进度
    if (config.onProgress) {
      uploadTask.onProgressUpdate((res) => {
        config.onProgress!(res.progress)
      })
    }

    // 处理取消
    if (config.cancelToken) {
      config.cancelToken.promise.then(() => {
        uploadTask.abort()
      })
    }
  })
}

// 文件下载
export async function downloadFile(config: DownloadConfig): Promise<string> {
  return new Promise((resolve, reject) => {
    const authStore = useAuthStore()
    const downloadTask = uni.downloadFile({
      url: httpClient['baseURL'] + config.url,
      header: {
        'Authorization': `Bearer ${authStore.token}`,
        ...config.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.tempFilePath)
        } else {
          reject(new HttpError(
            '文件下载失败',
            ErrorType.SERVER,
            undefined,
            res.statusCode
          ))
        }
      },
      fail: (err) => {
        reject(new HttpError(
          err.errMsg || '文件下载失败',
          ErrorType.NETWORK
        ))
      }
    })

    // 处理进度
    if (config.onProgress) {
      downloadTask.onProgressUpdate((res) => {
        config.onProgress!(res.progress)
      })
    }

    // 处理取消
    if (config.cancelToken) {
      config.cancelToken.promise.then(() => {
        downloadTask.abort()
      })
    }
  })
}

// 创建取消令牌
export function createCancelToken(): CancelToken {
  return httpClient.createCancelToken()
}

// 取消所有请求
export function cancelAllRequests(): void {
  httpClient.cancelAll()
}

// 导出类型
export type {
  RequestConfig,
  BaseResponse,
  PageResponse,
  CancelToken
}

// 导出错误相关
export { HttpError, ErrorType }

// 导出 httpClient 实例供高级用法
export { httpClient }

// 兼容旧版本 API
export default {
  get: http.get,
  post: http.post,
  request: http.request,
  ipAddress: import.meta.env.VITE_API_URL || 'https://api.volcore.xyz'
}

// 使用示例：
// import { http, createCancelToken } from '@/utils/http'
//
// // 基础用法
// const data = await http.get('/api/users')
// const result = await http.post('/api/users', { name: 'John' })
//
// // 带类型
// interface User {
//   id: number
//   name: string
// }
// const user = await http.get<User>('/api/users/1')
//
// // 取消请求
// const cancelToken = createCancelToken()
// http.get('/api/data', {}, { cancelToken })
//   .catch(error => {
//     if (error.isCancel) {
//       console.log('请求已取消')
//     }
//   })
// cancelToken.cancel('用户取消了请求')
//
// // 文件上传
// const fileUrl = await uploadFile({
//   url: '/api/upload',
//   filePath: tempFilePath,
//   onProgress: (progress) => {
//     console.log('上传进度:', progress)
//   }
// }) 